<?php
namespace App\Repositories;



use App\Models\Coach;
use App\Models\Comment;
use App\Models\Reply;
use App\Models\School;
use App\Models\SchoolConfig;
use App\Models\Student;
use App\Models\StudentState;
use App\Models\StudentTime;
use App\Models\Subscribe;
use App\Models\SyllabusTime;
use App\Models\TcpDevloc;
use App\Models\TcpPutime;
use App\Models\TcpPutimesImg;
use App\Models\TcpStudytime;
use App\Models\Trainingcar;
use App\Models\VideoLearn;
use Carbon\Carbon;

class PutimesRepository extends BaseRepository
{
    public $error = '';
    public function __construct(
        TcpStudytime $tcpStudytime
    )
    {
        $this->model = $tcpStudytime;
    }
    public function getSyllausTime($id)
    {
        $student = Student::where('id',$id)->first();
        if(!$student){
            $this->error = '该学员不存在';
            return false;
        }

        $syllabus_time = SyllabusTime::where('traintype',$student->traintype)->get();

        $school_config = SchoolConfig::where('school_id', $student->school_id)->first();
        $sch_putime_length = $school_config ? $school_config->sch_putime_length : 45;

        foreach ($syllabus_time as $v){
            switch ($v->km){
                case 1:
                    $a =  StudentTime::where('km', 1)->where('student_id', $id)->first();
                    $syllabus_time->km1sumperiod = $v->hour;
                    $syllabus_time->km1accomplish = $a ? number_format($a->countime/60/$sch_putime_length) : 0;
                    break;
                case 2:
                    $a =  StudentTime::where('km', 2)->where('student_id', $id)->first();
                    $syllabus_time->km2sumperiod = $v->hour;
                    $syllabus_time->km2accomplish = $a ? number_format($a->countime/60/$sch_putime_length) : 0;
                    break;
                case 3:
                    $a =  StudentTime::where('km', 3)->where('student_id', $id)->first();
                    $syllabus_time->km3sumperiod = $v->hour;
                    $syllabus_time->km3accomplish = $a ? number_format($a->countime/60/$sch_putime_length) : 0;
                    break;
                case 4:
                    $a =  StudentTime::where('km', 4)->where('student_id', $id)->first();
                    $syllabus_time->km4sumperiod = $v->hour;
                    $syllabus_time->km4accomplish = $a ? number_format($a->countime/60/$sch_putime_length) : 0;
                    break;
            }

            $v->accomplish = $a ? number_format($a->countime/60) : 0;
        }
        return $syllabus_time;
    }
    /**
     * 资源列表 我的培训
     * @param  array $data 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @param  string $size 分页大小（存在默认值）
     * @return Illuminate\Support\Collection
     */
    public function index($data=[], $extra='', $size='3')
    {
        $student = Student::where('id',$data['userid'])->first();
        if(!$student){
            $this->error = '该学员不存在';
            return false;
        }

        $syllabus_time = SyllabusTime::where('traintype',$student->traintype)->get();

        $list['syllabus'] = $syllabus_time;

        $list['count'] = [
            //科目一理论
            'km1theory'=>$this->model->where('stunum',$student->stunum)->where('km',1)->where('type',4)->sum('duration'),
            //科目一面授
            'km1scene'=>$this->model->where('stunum',$student->stunum)->where('km',1)->where('type',1)->sum('duration'),
            //科目二实操
            'km2operation'=>$this->model->where('stunum',$student->stunum)->where('km',2)->where('type',2)->sum('duration'),
            //科目二模拟
            'km2simulate'=>$this->model->where('stunum',$student->stunum)->where('km',2)->where('type',3)->sum('duration'),
            //科目三实操
            'km3operation'=>$this->model->where('stunum',$student->stunum)->where('km',3)->where('type',2)->sum('duration'),
            //科目三模拟
            'km3simulate'=>$this->model->where('stunum',$student->stunum)->where('km',3)->where('type',3)->sum('duration'),
            //科目四理论
            'km4theory'=>$this->model->where('stunum',$student->stunum)->where('km',4)->where('type',4)->sum('duration'),
            //科目四面授
            'km4scene'=>$this->model->where('stunum',$student->stunum)->where('km',4)->where('type',1)->sum('duration'),
        ];
        foreach ($list['syllabus'] as $v){
            switch ($v->km){
                case 1:
                    $a =  StudentTime::where('km', 1)->where('student_id', $student->id)->first();
                    break;
                case 2:
                    $a =  StudentTime::where('km', 2)->where('student_id', $student->id)->first();
                    break;
                case 3:
                    $a =  StudentTime::where('km', 3)->where('student_id', $student->id)->first();
                    break;
                case 4:
                    $a =  StudentTime::where('km', 4)->where('student_id', $student->id)->first();
                    break;
            }

            $v->accomplish = $a ? floor($a->countime/60) : 0;
        }

        $log = $this->model->where('stunum',$student->stunum)->where('km',$data['type'])->orderBy('created_at','desc')->take($size)
            ->select('id','inscode','stunum','coachnum','carnum','simunum','subjcode','classid','km','type','starttime','endtime','duration','mileage','is_evaluate','is_complaint')->get();
        if($log)
        {
            foreach ($log as $v)
            {
                if($v->type==2)
                {
                    $putimes = TcpPutime::where('stunum',$v->stunum)->where('classid',$v->classid)->where('jishi_check',1)->count();
                    $v->valid = $putimes?$putimes:0;

                    $no_putimes = TcpPutime::where('stunum',$v->stunum)->where('classid',$v->classid)->where('jishi_check',2)->count();
                    $v->no_valid = $no_putimes?$no_putimes:0;

                    $coach = Coach::where('coachnum',$v->coachnum)->first();
                    $v->coachname = $coach?$coach->name:'';
                    $car =  Trainingcar::where('carnum',$v->carnum)->first();
                    $v->licnum = $car?$car->licnum:'';
                    $v->classname = '';

                }else
                {
                    if($v->is_valid == 0){
                        $v->valid = 0;
                        $v->no_valid = 0;
                    }else if($v->is_valid == 1){
                        $v->no_valid = 0;
                        $v->valid = $v->duration;
                    }else {
                        $v->valid = 0;
                        $v->no_valid = $v->duration;
                    }
                    $v->coachname = '';
                    $v->licnum = '';
                    $video_info = VideoLearn::where('study_time_id', $v->id)->where('student_id', $data['userid'])->first();
                    $v->classname = $video_info ? $video_info->video->name : '';
                }
            }
        }

        $list['log'] = $log;

        return $list;

    }

    /**
     * 资源列表 我的培训
     * @param  array $parem 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @param  string $size 分页大小（存在默认值）
     * @return Illuminate\Support\Collection
     */
    public function putimeLog($parem=[], $extra='', $size='10')
    {
        $student = Student::where('id',$parem['userid'])->first();
        if(!$student){
            $this->error = '该学员不存在';
            return false;
        }
        $query = $this->model->where('stunum',$student->stunum);
        if($parem['type']==2){
            $query->where('is_evaluate',0)->whereNotIn('km', [1,4]);
        }elseif ($parem['type']==3){
            $query->where('is_complaint',1)->whereNotIn('km', [1,4]);
        }

        if($parem['km']){
            $query->where('km',$parem['km']);
        }


        $list = $query->orderBy('created_at','desc')
            ->select('id','inscode','stunum','coachnum','carnum','simunum','subjcode','classid','km','type','starttime','endtime','duration','mileage','is_evaluate','is_complaint')
            ->limit($size)
            ->offset(($parem['page'] - 1) * $size)
            ->get();

        if($list->count())
        {
            foreach ($list as $v)
            {
                if($v->type==2)
                {
                    $putimes = TcpPutime::where('stunum',$v->stunum)->where('classid',$v->classid)->where('jishi_check',1)->count();
                    $v->valid = $putimes?$putimes:0;
                    $no_putimes = TcpPutime::where('stunum',$v->stunum)->where('classid',$v->classid)->where('jishi_check',2)->count();
                    $v->no_valid = $no_putimes?$no_putimes:0;
                    $coach = Coach::where('coachnum',$v->coachnum)->first();
                    $v->coachname = $coach?$coach->name:'';
                    $car =  Trainingcar::where('carnum',$v->carnum)->first();
                    $v->licnum = $car?$car->licnum:'';
                    $v->classname = '';

                }else
                {
                    if($v->is_valid == 0){
                        $v->valid = 0;
                        $v->no_valid = 0;
                    }else if($v->is_valid == 1){
                        $v->no_valid = 0;
                        $v->valid = $v->duration;
                    }else{
                        $v->valid = 0;
                        $v->no_valid = $v->duration;
                    }
                    $v->coachname = '';
                    $v->licnum = '';
                    $video_info = VideoLearn::where('study_time_id', $v->id)->where('student_id',$parem['userid'])->first();
                    $v->classname = $video_info ? $video_info->video->name : '';
                }
            }
        }


        if($parem['km']){

            $evaluatenum = $this->model->where('stunum',$student->stunum)->where('km', $parem['km'])->where('is_evaluate',0)->whereNotIn('km', [1,4])->count();

        }else{
            $evaluatenum = $this->model->where('stunum',$student->stunum)->where('is_evaluate',0)->whereNotIn('km', [1,4])->count();
        }


        if($parem['km']){
            $complaintnum = $this->model->where('stunum',$student->stunum)->where('km', $parem['km'])->where('is_complaint',1)->whereNotIn('km', [1,4])->count();
        }else{
            $complaintnum = $this->model->where('stunum',$student->stunum)->where('is_complaint',1)->whereNotIn('km', [1,4])->count();
        }

        $total = $this->model->where('stunum',$student->stunum)->count();
        if($parem['km']){
            $total = $this->model->where('stunum',$student->stunum)->where('km', $parem['km'])->count();
        }

        $data['count'] = [
            'evaluatenum' => $evaluatenum,
            'complaintnum' => $complaintnum,
            'total' => $total
        ];
        $data['list'] = $list;

        return $data;
    }

    /**
     * @param  array $parem 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @return mixed
     */
    public function teachingRecord($parem=[], $extra='')
    {
        $putimeLog = $this->model->where('id',$parem['putime_id'])->first();
        $data = [];
        if($parem['type']==1){//详情
            $coach = Coach::where('coachnum',$putimeLog->coachnum)->first();
            $car =  Trainingcar::where('carnum',$putimeLog->carnum)->first();

            $data['list'] = [
                'valid_putime' =>TcpPutime::where('stunum',$putimeLog->stunum)->where('classid',$putimeLog->classid)->where('jishi_check',1)->count(),//有效学时
                'novalid_putime' => TcpPutime::where('stunum',$putimeLog->stunum)->where('classid',$putimeLog->classid)->where('jishi_check',2)->count(),//无效学时
                'km'=>$putimeLog->km,
                'type'=>$putimeLog->type,
                'starttime'=>$putimeLog->starttime,
                'endtime'=>$putimeLog->endtime,
                'duration'=>$putimeLog->duration,
                'mileage'=>$putimeLog->mileage * 0.1,
                'coachname'=>$coach?$coach->name:'',
                'licnum'=>$car?$car->licnum:'',
                'classname'=>getPutimeName($putimeLog->subjcode),
            ];

            if($putimeLog->km == 1 || $putimeLog->km == 4){
                if($putimeLog->is_valid == 1){
                    $data['list'] ['valid_putime'] = $putimeLog->duration;
                }elseif($putimeLog->is_valid == 2){
                    $data['list'] ['novalid_putime'] = $putimeLog->duration;
                }
            }

            $video_info = VideoLearn::where('study_time_id', $putimeLog->id)->where('student_id',$parem['userid'])->first();
            $data['list']['classname'] = $video_info ? $video_info->video->name : '';


            //查询培训照片
            if($putimeLog->type==2){
                $img = TcpPutimesImg::where('stunum',$putimeLog->stunum)->where('inscode',$putimeLog->inscode)->where('classid',$putimeLog->classid)
                    ->select('img_type','img_url','ptime','jishi_check_reason','jishi_check')
                    ->get();
                $data['img'] = $img;
            }else{
                $img = [
                    [
                        'img_type'=>17, //登陆拍照
                        'img_url'=>$putimeLog->photo1url,
                        'ptime'=>$putimeLog->starttime,
                        'jishi_check'=> 1,
                        'jishi_check_reason'=>''
                    ],
                    [
                        'img_type'=>18,//登出拍照
                        'img_url'=>$putimeLog->photo3url,
                        'ptime'=>$putimeLog->endtime,
                        'jishi_check'=> 1,
                        'jishi_check_reason'=>''
                    ],
                ];
                if($putimeLog->photo2){
                    $photo2 = [
                        'img_type'=>19,//培训过程拍照
                        'img_url'=>$putimeLog->photo2url,
                        'ptime'=>date('Y-m-d H:i:s',strtotime($putimeLog->starttime)+900),
                        'jishi_check'=> 1,
                        'jishi_check_reason'=>''
                    ];
                    $img[] = $photo2;
                }
                $data['img'] = $img;
            }
        }elseif ($parem['type']==2){//轨迹
            if($putimeLog->type==2){
                $coach = Coach::where('coachnum',$putimeLog->coachnum)->first();//教练信息
                $car =  Trainingcar::where('carnum',$putimeLog->carnum)->first();//车辆信息
                $student = Student::where('stunum',$putimeLog->stunum)->first();//学员信息

                $data['list'] = [
                    'km'=>$putimeLog->km,
                    'type'=>$putimeLog->type,
                    'starttime'=>$putimeLog->starttime,
                    'endtime'=>$putimeLog->endtime,
                    'duration'=>$putimeLog->duration,
                    'mileage'=>$putimeLog->mileage * 0.1,
                    'coachname'=>$coach?$coach->name:'',
                    'licnum'=>$car?$car->licnum:'',
                    'stuname'=>$student?$student->name:'',
                    'stuphoto'=>$student?$student->photo:'',
                    'traintype'=>$student?$student->traintype:''
                ];


                $devnum = TcpPutime::where('classid',$putimeLog->classid)->first()->devnum;

                $tmppoints = [];
//                $datas = TcpDevloc::where('classid',$putimeLog->classid)->where('stunum',$putimeLog->stunum)->orderBy('ctime','asc')->get();//从mongo获取gps
                $datas = TcpDevloc::where('devnum', $devnum)->where('ctime','>=', (string)strtotime($putimeLog->starttime))->where('ctime', '<=', (string)strtotime($putimeLog->endtime))->orderBy('ctime','asc')->get();
//                if($datas){
//                    foreach($datas as $v){
//                        $tmppoints[] = ['lng'=>changepoint($v->lon),'lat'=>changepoint($v->lat)];
//                    }
//                }

                $start_time = strtotime($putimeLog->starttime);
                $end_time = strtotime($putimeLog->endtime);
                if($datas){
                    foreach($datas as $v){
                        if($v->ctime>= $start_time && $v->ctime<=$end_time){ //排除不是范围的时间
                            $tmppoints[] = ['lng'=>changepoint($v->lon),'lat'=>changepoint($v->lat)];
                        }
                    }
                }


              /*  //写死的测试数据  可删除
                $datas = [[105.013718,31.395968],[105.016984,31.398671],[105.019784,31.400988],[105.02305,31.403689]];
                foreach($datas as $item){
                    $tmppoints[] = ['lng'=>$item[0],'lat'=>$item[1]];
                }*/

                $data['gps'] = $tmppoints;

            }
        }elseif ($parem['type']==3){//图表
            if($putimeLog->type==2){
                $maxspeed = TcpPutime::where('stunum',$putimeLog->stunum)->where('classid',$putimeLog->classid)->max('maxspeed');
//                $avgspeed = TcpPutime::where('stunum',$putimeLog->stunum)->where('classid',$putimeLog->classid)->avg('maxspeed');
                $list = TcpPutime::where('stunum',$putimeLog->stunum)->where('classid',$putimeLog->classid)
                                ->select('runningspeed','maxspeed','rev','mileage','rectime')
                                ->orderBy('rectime', 'asc')
                                ->get();
                $data['count'] = [
                    'maxspeed'=>$maxspeed ? $maxspeed / 10 : 0,
                    'avgspeed'=> floatval(number_format(($putimeLog->mileage / 10 )/ ($putimeLog->duration/60),2)),
                ];

                if($list){

                    foreach($list as $k => $v){
                        $list[$k]['runningspeed'] = $v['runningspeed'] / 10;
                        $list[$k]['maxspeed'] = $v['maxspeed'] / 10;
                        $list[$k]['time'] = ceil((strtotime($v['rectime']) - strtotime($list[0]['rectime'])) / 60);
                    }
                }

                $data['statics'] = $list;
            }
        }


        $data['is_evaluate'] = $putimeLog->is_evaluate;
        $data['is_complaint'] = $putimeLog->is_complaint;

        return $data;
    }



    /**
     * 存储odb
     * @param $inputs
     */
    public function store($inputs, $extra = '')
    {

    }


    /**
     * 更新
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input,$extra = '')
    {
        $model = $this->getById($id);
        return $this->save($model,$input);
    }


    /**
     * 编辑特定id资源
     * @param  int $id 资源id
     * @param  string|array $extra 可选额外传入的参数
     * @return Illuminate\Support\Collection
     */
    public function edit($id, $extra)
    {

    }

    /**
     * @param $model
     * @param $inputs
     * @param bool $falg
     * @return mixed
     */
    public function save($model , $inputs , $falg = false)
    {
        return $model;
    }


    /**
     * @param $model
     * @param $inputs
     * @param bool $falg
     * @return mixed
     */
    public function noValidePutime(Student $student_info, $classid, $page, $size)
    {
        $data['count'] = TcpPutime::where('stunum',$student_info->stunum)->where('classid',$classid)
                                     ->where('jishi_check',2)->count();

        $data['list'] = TcpPutime::where('stunum',$student_info->stunum)->where('classid',$classid)
                        ->where('jishi_check',2)
                        ->limit($size)
                        ->offset(($page - 1) * $size)
                        ->get();//无效学时


        if($data['list']){

            foreach($data['list'] as $list){
                $list->maxspeed = $list->maxspeed * 0.1;
                $list->runningspeed = $list->runningspeed * 0.1;
                $list->mileage = $list->mileage * 0.1;
            }
        }

        return $data;
    }


    /**
     * 培训记录
     */
    public function trainRecord()
    {

    }


    /**
     * 投诉记录
     */
    public function complain(Student $student, $putime_id, $content)
    {


//         $putime_info = $this->model->find($putime_id);

         $subscribe_info = Subscribe::find($putime_id);

         $data['student_id'] = $student->id;
         $data['cid'] = $putime_id;

         $coach = Coach::where('id', $subscribe_info->coach_id)->first();

         $data['coach_id'] = $coach ? $coach->id: '';
         $data['item_type'] = 3;
         $data['state'] = $content;
         $data['createtime'] = time();

//        $putime_info->is_complaint = 1;
//        $putime_info->save();

        $subscribe_info->is_complained = 1;
        $subscribe_info->save();

         return StudentState::insert($data);
    }

    /**
     * 查看学时学员投诉信息
     * @param Student $student
     * @param $putime_id
     */
    public function showComplaint(Student $student, $putime_id)
    {
        //$putime_info = $this->model->leftJoin('coachs', 'coachs.coachnum', '=', 'tcp_studytimes.coachnum')->select('tcp_studytimes.*','coachs.name as coachname')->find($putime_id);

        $subscribe_info = Subscribe::leftJoin('coachs', 'coachs.id', '=', 'yy_subscribes.coach_id')
                                    ->leftJoin('yy_put_periods', 'yy_put_periods.id', '=', 'yy_subscribes.putime_id')
                                    ->select('yy_put_periods.startime','yy_put_periods.endtime','yy_put_periods.km','coachs.name as coachname')
                                    ->where('yy_subscribes.id',$putime_id)
                                    ->first();

        $complain_info = StudentState::where('cid', $putime_id)->where('student_id', $student->id)->where('item_type','3')->first();

//        $reply_info = Reply::where('item_id',$complain_info->id)->first();
//        if($reply_info){
//            //4驾校，5教练，3学员',
//            if($reply_info->from_type == 3){
//                $info = Student::where('id', $reply_info->from_id)->first();
//                $reply_info->nickname = $info->name;
//                $reply_info->phone = $info->phone;
//            }elseif($reply_info->from_type == 4){
//                $info = School::where('id', $reply_info->from_id)->first();
//                $reply_info->nickname = $info->shortname;
//                $reply_info->phone = $info->phone;
//            }elseif($reply_info->from_type == 5){
//                $info =  Coach::where('id', $reply_info->from_id)->first();
//                $reply_info->nickname = $info->name;
//                $reply_info->phone = $info->mobile;
//            }
//        }

        return ['putime_info' => $subscribe_info, 'complain_info' => $complain_info];
    }

    /**
     * 评价记录
     */
    public function comment(Student $student, $putime_id, $data)
    {
        if($data['to_type']==2){
            $subscribe_info = Subscribe::find($putime_id);
            $coach = Coach::find($subscribe_info->coach_id);
        }else{

            $putime_info = $this->model->find($putime_id);
            $coach = Coach::where('coachnum', $putime_info->coachnum)->first();
        }


        $comment['student_id'] = $student->id;
        $comment['cid'] = $putime_id;


        $comment['coach_id'] = $coach ? $coach->id: '';
        $comment['createtime'] = time();
        $comment['comment'] = $data['type'];
        $comment['xsqr'] = $data['content'];
        $comment['zynl'] = 0;
        $comment['jxtd']= 0;
        $comment[ 'sjgn']= 0;
        $comment['ljcd']= 0;
        $comment['ip']= '';
        $comment['views']= 0;
        $comment['isdelete']= 0;
        $comment['type'] = $data['to_type'];

        if($data['to_type']==2){
            $subscribe_info->is_comment = 1;
            $subscribe_info->save();
        }else{
            $putime_info->is_evaluate = 1;
            $putime_info->save();
        }

        return Comment::insert($comment);
    }


    /**
     * 查看学时学员评价信息
     * @param Student $student
     * @param $putime_id
     */
    public function showComment (Student $student, $putime_id)
    {
//        $putime_info = $this->model->find($putime_id);

        $subscribe_info =  Subscribe::leftJoin('coachs', 'coachs.id', '=', 'yy_subscribes.coach_id')
                                    ->leftJoin('yy_put_periods', 'yy_put_periods.id', '=', 'yy_subscribes.putime_id')
                                    ->select('yy_put_periods.startime','yy_put_periods.endtime','yy_put_periods.km','coachs.name as coachname')
                                    ->where('yy_subscribes.id',$putime_id)
                                    ->first();

        $comment_info = Comment::where('cid', $putime_id)->where('student_id', $student->id)->first();

        return ['putime_info' => $subscribe_info, 'comment_info' => $comment_info];
    }


    /**
     * 教练查看培训工时信息
     * @param Coach $coach
     * @param string $type
     * @param int $page
     * @param int $size
     */
    public function coachTrainRecords(Coach $coach, $type = '', $page = 1, $size = 15)
    {
        $total_query = $this->model->where('coachnum', $coach->coachnum);


        $total = $total_query->count();
        //本年度
        $year_total = $total_query->where('starttime','>=',date('Y-01-01'))->count();
        //本月度
        $month_total = $total_query->where('starttime','>=',date('Y-m-01'))->count();


        $list_query = $this->model->leftJoin('students','students.stunum','=','tcp_studytimes.stunum')
                                ->select('tcp_studytimes.*','students.id as stuid','students.photo','students.name','students.phone')
                                ->where('coachnum', $coach->coachnum);
        //本年度
        if($type == '1'){
            $query = $list_query->where('starttime','>=',date('Y-01-01'));
            //本月度
        }elseif($type == '2'){
            $query = $list_query->where('starttime','>=',date('Y-m-01'));
        }

        $list = $list_query->orderBy('starttime','desc')
                        ->offset(($page - 1) * $size)->limit($size)
                        ->get();


        return [$list, $total, $year_total, $month_total];
    }


}